package org.wanho.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * Author：汤小洋
 * Date：2023-04-24 14:31
 * Description：<描述>
 */
@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Random random = new Random();

        //在内存中创建一个画板
        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics graphics = image.getGraphics();

        //设置填充的背景
        //将填充的背景设置的与画板大小
        graphics.fillRect(0,0,50,25);

        //设置画笔的颜色
        //使用随机色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));

        //设置字体
        graphics.setFont(new Font("宋体", Font.BOLD+ Font.ITALIC,18));

        //设置验证码的内容
        //要求随机生成0-9a-z
        String s = "0123456789qwertyuiopasdfghjklzxcvbnm";
        StringBuffer code = new StringBuffer();
        for(int i = 0; i < 4; i++){
            code.append(s.charAt(random.nextInt(s.length())));
        }

        //将生成的随机数存放到session
        //方便使用的时候进行校验
        request.getSession().setAttribute("randCode",code.toString());
        graphics.drawString(code.toString(),5,18);
        System.out.println("验证码:"+code);

        //输出验证码图片
        OutputStream out = response.getOutputStream();

        ImageIO.write(image,"JPEG",out);
    }
}